package com.ssm.controller;

import com.ssm.util.ResultData;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Lenovo
 * @version 1.0
 * @description TODO
 * @date 10/11/2023 上午10:38
 */
@RestController
public class uploadImage {
    @RequestMapping("/upload")
    public ResultData upload(MultipartFile source, HttpServletRequest request) throws IOException {
        String originalFilename = source.getOriginalFilename( );
        String prefix = UUID.randomUUID( ).toString( );
        String suffix = FilenameUtils.getExtension(originalFilename);
        String filename = prefix+"."+suffix;
        String realPath = request.getServletContext( ).getRealPath("/upload_file");
        File parentFile = new File(realPath);
        if (!parentFile.exists()) {
            parentFile.mkdir();
        }
        source.transferTo(new File(parentFile,filename));
        return ResultData.ok("/upload_file/"+filename);
    }

    @RequestMapping("/download")
    public void download(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {

        String realPath = request.getServletContext( ).getRealPath("/upload_file");
        String filepath = realPath+"/"+filename;

        //设置响应头 告知浏览器，要以附件的形式保存内容
        //浏览器显示的下载文件名
        response.addHeader("content-disposition","attachment;filename="+filename);
        response.setContentType("multipart/form-data");
        //读取目标文件，写出给客户端
        IOUtils.copy(new FileInputStream(filepath),response.getOutputStream());
    }
}
